﻿using RazorEngine;
using SlamDunk.CMS.Common;
using SlamDunk.CMS.Common.Attributes;
using SlamDunk.CMS.Handler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using SlamDunk.CMS.BLL;
using SlamDunk.CMS.Model;

namespace SlamDunk.CMS.Controllers
{
    /// <summary>
    /// 控制器父类
    /// </summary>
    public class BaseController : Controller
    {
        #region 00.授权过滤器，验证用户是否登录
        /// <summary>
        /// 授权过滤器，验证用户是否登录
        /// </summary>
        /// <param name="filterContext">过滤器上下文</param>
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            //判断用户是否登录，Action上是否贴有无需过滤标签
            if (!OperateContext.Current.IsLogin() && !CommonAssistant.HasAttribute<SkipFilterAttribute>(filterContext.ActionDescriptor))
            {
                //filterContext.HttpContext.Response.Redirect("/Admin/User/Login");
                filterContext.HttpContext.Response.Write("<script>window.top.location.href='/Admin/User/Login';</script>");
            }
        }
        #endregion

        #region 01.实例化业务层
        /// <summary>
        /// 实例化业务层
        /// </summary>
        private readonly BLL.ArticleBll ArticleBll = BLL.ArticleBll.CreateInstance();
        private readonly BLL.ChannelBll ChannelBll = BLL.ChannelBll.CreateInstance();
        private readonly BLL.PhotoAlbumBll PhotoAlbumBll = BLL.PhotoAlbumBll.CreateInstance();
        private readonly BLL.PhotoBll PhotoBll = BLL.PhotoBll.CreateInstance();
        #endregion

        #region 02.※ 生成静态页之内容页 ※
        /// <summary>
        /// 生成静态页之内容页
        /// </summary>
        /// <param name="model">文章实体对象</param>
        protected void CreateDetailHtml(Model.Article currentModel)
        {
            //判断内容页模板是否存在
            if (!currentModel.Channel.DetailTemplate.IsNullOrEmpty())
            {
                //预编译分支模板
                PreCompileSub();
                //读取模板文件
                string detailTmp = FileAssistant.Current.ReadFile(Server.MapPath(currentModel.Channel.DetailTemplate));
                //获取新当前文章的上一篇与下一篇文章对象
                Model.Article prevModel = ArticleBll.GetPrevModel(currentModel.Id, currentModel.ChannelId);
                Model.Article nextModel = ArticleBll.GetNextModel(currentModel.Id, currentModel.ChannelId);
                if (prevModel != null)
                {
                    //填充上一篇文章的下一篇字段
                    prevModel.NextPage = currentModel.GetLinkString();
                    ArticleBll.Update(prevModel);
                    //渲染Html并生成内容页
                    string prevArticle = Razor.Parse(detailTmp, prevModel);
                    FileAssistant.Current.WriteFile(Server.MapPath(prevModel.GetUrl()), prevArticle);
                    //填充当前文章的上一篇字段
                    currentModel.PrevPage = prevModel.GetLinkString();
                    ArticleBll.Update(currentModel);
                }
                else
                {
                    //填充当前文章的上一篇字段
                    currentModel.PrevPage = "无";
                    ArticleBll.Update(currentModel);
                }
                if (nextModel != null)
                {
                    //填充下一篇文章的上一篇字段
                    nextModel.PrevPage = currentModel.GetLinkString();
                    ArticleBll.Update(nextModel);
                    //渲染Html并生成内容页

                    SlamDunk.CMS.Model.ChannelView currentChannel = nextModel.Channel.ToViewModel();

                    string nextArticle = Razor.Parse(detailTmp, nextModel);
                    FileAssistant.Current.WriteFile(Server.MapPath(nextModel.GetUrl()), nextArticle);
                    //填充当前文章的下一篇字段
                    currentModel.NextPage = nextModel.GetLinkString();
                    ArticleBll.Update(currentModel);
                }
                else
                {
                    //填充当前文章的下一篇字段
                    currentModel.NextPage = "无";
                    ArticleBll.Update(currentModel);
                }
                //渲染Html并生成内容页
                string currentArticle = Razor.Parse(detailTmp, currentModel);
                FileAssistant.Current.WriteFile(Server.MapPath(currentModel.GetUrl()), currentArticle);
            }
        }
        #endregion

        #region 03.※ 生成静态页之列表页 ※
        /// <summary>
        /// 生成静态页之列表页
        /// </summary>
        /// <param name="currentModel">栏目实体对象</param>
        protected void CreateListHtml(Model.Channel currentModel)
        {
            //判断列表页模板是否存在
            if (!currentModel.ListTemplate.IsNullOrEmpty())
            {
                //预编译分支模板
                PreCompileSub();
                //读取列表页模板
                string listTmp = FileAssistant.Current.ReadFile(Server.MapPath(currentModel.ListTemplate));
                //获取该栏目文章总页数
                int pageCount = ChannelBll.GetPageCount(currentModel);
                for (int i = 1; i <= pageCount; i++)
                {
                    int rowCount;
                    List<Model.ArticleViewForRead> list = ArticleBll.GetModelList(i, currentModel.PageSize, out rowCount, currentModel.Id).Select(y => y.ToViewModel()).ToList();
                    if (list.Count > 0)
                    {
                        string listPage = Razor.Parse(listTmp, new
                        {
                            ArticleList = list,
                            FirstPage = 1,
                            LastPage = pageCount,
                            PrevPage = i - 1 <= 1 ? 1 : i - 1,
                            NextPage = i + 1 >= pageCount ? pageCount : i + 1,
                            CurrentPage = i,
                            PageCount = pageCount,
                            RowCount = rowCount
                        });
                        FileAssistant.Current.WriteFile(Server.MapPath(string.Format("{0}/List-{1}.html", currentModel.SaveDirectory, i)), listPage);
                    }
                }
            }
        }
        #endregion

        #region 04.※ 生成静态页之聚合页（递归） ※
        /// <summary>
        /// 生成静态页之聚合页
        /// </summary>
        /// <param name="model">栏目实体对象</param>
        protected void CreateIndexHtml(Model.Channel currentModel)
        {
            //判断聚合页模板是否存在
            if (!currentModel.IndexTemplate.IsNullOrEmpty())
            {
                //预编译分支模板
                PreCompileSub();
                //读取聚合页模板
                string indexTmp = FileAssistant.Current.ReadFile(Server.MapPath(currentModel.IndexTemplate));
                string indexPage = Razor.Parse(indexTmp);
                FileAssistant.Current.WriteFile(Server.MapPath(string.Format("{0}/Index.html", currentModel.SaveDirectory)), indexPage);
                //递归
                Model.Channel pModel = ChannelBll.GetModel(currentModel.PId);
                if (pModel != null)
                {
                    CreateIndexHtml(pModel);
                }
            }
        }
        #endregion

        #region 05.※ 生成静态页之聚合页（非递归） ※
        /// <summary>
        /// 生成静态页之聚合页
        /// </summary>
        /// <param name="model">栏目实体对象</param>
        protected void CreateIndexHtmlNoRecursion(Model.Channel currentModel)
        {
            //判断聚合页模板是否存在
            if (!currentModel.IndexTemplate.IsNullOrEmpty())
            {
                //预编译分支模板
                PreCompileSub();
                //读取聚合页模板
                string indexTmp = FileAssistant.Current.ReadFile(Server.MapPath(currentModel.IndexTemplate));
                string indexPage = Razor.Parse(indexTmp);
                FileAssistant.Current.WriteFile(Server.MapPath(string.Format("{0}/Index.html", currentModel.SaveDirectory)), indexPage);
            }
        }
        #endregion

        #region 06.※ 生成静态页之首页 ※
        /// <summary>
        /// 生成静态页之首页
        /// </summary>
        protected void CreateHomeHtml()
        {
            //获取存储首页保存路径及模板的栏目对象
            Model.Channel rootChannel = ChannelBll.GetModel(1);
            //判断首页模板是否存在
            if (!rootChannel.IndexTemplate.IsNullOrEmpty())
            {
                //预编译分支模板
                PreCompileIndex();
                //读取首页模板
                string homeTmp = FileAssistant.Current.ReadFile(Server.MapPath(rootChannel.IndexTemplate));
                string homePage = Razor.Parse(homeTmp, new { Title = "哈尔滨工业大学管理学院招生信息网" });
                FileAssistant.Current.WriteFile(Server.MapPath(string.Format("{0}/Index.html", rootChannel.SaveDirectory)), homePage);
                /*************************************************************/
                //生成搜索列表静态页
                CreateSearchResultPage();
                //生成本科历年分数线静态页
                CreateScoreLinePage();
                //生成硕士历年分数线静态页
                CreateMasterScoreLinePage();
                //生成相册列表页
                CreateAlbumListHtml();
                //生成相册内容页
                CreateAlbumHtml();
            }
        }
        #endregion

        #region 07.将绝对路径转换成相对路径方法
        /// <summary>
        /// 将绝对路径转换成相对路径方法
        /// </summary>
        /// <param name="mapPath">绝对路径</param>
        /// <returns>相对路径</returns>
        protected string ToRelativePath(string mapPath)
        {
            string root = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath);//获取程序根目录
            string relitavePath = mapPath.Replace(root, string.Empty); //转换成相对路径
            relitavePath = relitavePath.Replace(@"\", @"/");
            return relitavePath;
        }
        #endregion

        #region 08.预编译分支模板——首页
        /// <summary>
        /// 预编译分支模板——首页
        /// </summary>
        private void PreCompileIndex()
        {
            //读取分支模板
            string headTmp = FileAssistant.Current.ReadFile(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["Head"]));
            string topTmp = FileAssistant.Current.ReadFile(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["Top"]));
            string footTmp = FileAssistant.Current.ReadFile(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["Foot"]));
            string bannerTmp = FileAssistant.Current.ReadFile(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["Banner"]));
            //预编译分支模板
            Razor.Compile(headTmp, "Head");
            Razor.Compile(topTmp, "Top");
            Razor.Compile(footTmp, "Foot");
            Razor.Compile(bannerTmp, "Banner");
        }
        #endregion

        #region 09.预编译分支模板——子页
        /// <summary>
        /// 预编译分支模板——子页
        /// </summary>
        private void PreCompileSub()
        {
            //读取分支模板
            string headTmp = FileAssistant.Current.ReadFile(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["Head"]));
            string topTmp = FileAssistant.Current.ReadFile(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["Top"]));
            string leftTmp = FileAssistant.Current.ReadFile(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["Left"]));
            string footTmp = FileAssistant.Current.ReadFile(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["Foot"]));
            string subBannerTmp = FileAssistant.Current.ReadFile(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["SubBanner"]));
            //预编译分支模板
            Razor.Compile(headTmp, "Head");
            Razor.Compile(topTmp, "Top");
            Razor.Compile(leftTmp, "Left");
            Razor.Compile(footTmp, "Foot");
            Razor.Compile(subBannerTmp, "SubBanner");
        }
        #endregion

        #region 10.生成本科历年分数线静态页
        /// <summary>
        /// 生成历年分数线静态页
        /// </summary>
        public void CreateScoreLinePage()
        {
            //预编译分支模板
            PreCompileSub();
            //读取模板
            string scoreLineTmp = FileAssistant.Current.ReadFile(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["ScoreLine"]));
            string scoreLinePage = Razor.Parse(scoreLineTmp, new { Title = "本科历年分数线" });
            FileAssistant.Current.WriteFile(Server.MapPath("/Html/ScoreLine/Index.html"), scoreLinePage);
        }
        #endregion

        #region 11.生成硕士历年分数线静态页
        /// <summary>
        /// 生成历年分数线静态页
        /// </summary>
        public void CreateMasterScoreLinePage()
        {
            //预编译分支模板
            PreCompileSub();
            //读取模板
            string masterTmp_T = FileAssistant.Current.ReadFile(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["MasterScoreLine_T"]));
            string masterTmp_L = FileAssistant.Current.ReadFile(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["MasterScoreLine_L"]));
            string masterPage_T = Razor.Parse(masterTmp_T, new { Title = "统招硕士历年分数线" });
            string masterPage_L = Razor.Parse(masterTmp_L, new { Title = "联考硕士历年分数线" });
            FileAssistant.Current.WriteFile(Server.MapPath("/Html/MasterScoreLine/Index_T.html"), masterPage_T);
            FileAssistant.Current.WriteFile(Server.MapPath("/Html/MasterScoreLine/Index_L.html"), masterPage_L);
        }
        #endregion

        #region 12.生成搜索列表静态页
        /// <summary>
        /// 生成搜索列表静态页
        /// </summary>
        public void CreateSearchResultPage()
        {
            //预编译分支模板
            PreCompileSub();
            //读取模板
            string searchResultTmp = FileAssistant.Current.ReadFile(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["SearchResult"]));
            string searchResultPage = Razor.Parse(searchResultTmp, new { Title = "搜索结果" });
            FileAssistant.Current.WriteFile(Server.MapPath("/Html/SearchResult.html"), searchResultPage);
        }
        #endregion

        #region 13.※ 生成相册列表页 ※
        /// <summary>
        /// 生成相册列表页
        /// </summary>
        protected void CreateAlbumListHtml()
        {
            //预编译分支模板
            PreCompileSub();
            //读取列表页模板
            string listTmp = FileAssistant.Current.ReadFile(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["PhotoAlbum"]));
            //获取该相册总页数
            int pageCount = PhotoAlbumBll.GetPageCount(16);
            //根据页容量遍历相册列表，生成相册列表静态页
            for (int i = 1; i <= pageCount; i++)
            {
                int rowCount;
                List<Model.PhotoAlbumView> list = PhotoAlbumBll.GetModelList(i, 16, out rowCount).Select(x => x.ToViewModel()).ToList();
                if (list.Count > 0)
                {
                    string listPage = Razor.Parse(listTmp, new
                    {
                        AlbumList = list,
                        FirstPage = 1,
                        LastPage = pageCount,
                        PrevPage = i - 1 <= 1 ? 1 : i - 1,
                        NextPage = i + 1 >= pageCount ? pageCount : i + 1,
                        CurrentPage = i,
                        PageCount = pageCount,
                        RowCount = rowCount
                    });
                    FileAssistant.Current.WriteFile(Server.MapPath(string.Format("/Html/PhotoAlbum/List-{0}.html", i)), listPage);
                }
            }
        }
        #endregion

        #region 14.生成相册内容页
        /// <summary>
        /// 生成相册内容页
        /// </summary>
        protected void CreateAlbumHtml()
        {
            //预编译分支模板
            PreCompileSub();
            //读取相册内容页模板
            string detailTmp = FileAssistant.Current.ReadFile(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["Photo"]));
            //获取所有相册
            List<Model.PhotoAlbum> albumList = PhotoAlbumBll.GetModelList();
            //遍历相册生成相册内容页
            foreach (Model.PhotoAlbum photoAlbum in albumList)
            {
                List<Model.Photo> photoList = PhotoBll.GetModelList(photoAlbum.Id);
                if (photoList.Count > 0)
                {
                    string detailPage = Razor.Parse(detailTmp, new { PhotoList = photoList });
                    FileAssistant.Current.WriteFile(Server.MapPath(string.Format("/Html/Photo/Album-{0}.html", photoAlbum.Id)), detailPage);
                }
            }
        }
        #endregion
    }
}
